$(function () {
    // 滚动固定选项卡
    eFixedFn('.scMenu-card', 1)
    //选项导航滚动定位
    headerOptionsFn()
    ajaxCommentList(1,5);


    var courseId = $("#courseId").val();
    getLiveCourseCatalogData(courseId);


    /**
     * 加载直播课程目录
     * @param courseId 课程ID
     */
    function getLiveCourseCatalogData(courseId) {
        setTimeout(function () {
            $.ajax({
                url: baseloaction +'/mobile/course/findLiveCatalog',
                type:'post',
                dataType:'html',
                data:{
                    'courseId':courseId
                },
                success:function (result) {
                    $("#live-course-catalog-box").html(result);
                   var liSize = $("#live-course-catalog-box").find("li");

                   if(liSize.length>7){
                       $('.liveCatalog-List-bx').css("height", "5rem")
                   }else{
                       $("#more-liveCatalog-btn").addClass("hide");
                   }
                }
            });
        },0);
    }
    function headerOptionsFn() {
        $('#header-nav').on('click', 'a.button', function () {
            var _this = $(this),
                _id = _this.data('id'),
                _top = Math.floor($("#"+_id).position().top);
            _this.addClass('active').siblings().removeClass('active')
            $('.content').scrollTop(_top+50)
        })
    }

    //检查时是否是分享出去的页面，添加悬浮按钮
    checkSharedPage();
    validationStatus();
    if(initCatalogId > 0){
        if(status!=1){
            return;
        }
        goPlay(courseId,courseId,initCatalogId,playCallback);
    }
    $("body").on('click','div.wm-buttons-tab>a',function () {
        var _this = $(this);
        var _index = _this.index();
        if(_index == 0){//详情
            if(!buy){
                Zepto('nav.course-info-bar-tab').removeClass('mfHide');
            }
        }else if(_index == 1){//目录
            if(!_this.hasClass('active')){
                Zepto('nav.course-info-bar-tab').addClass('mfHide');
            }
        }else if(_index==2){//反馈
            if(!_this.hasClass('active')){
                Zepto('nav.course-info-bar-tab').addClass('mfHide');
            }
        }
    }).on('click','#c-sign-up-btn',function () {//立即报名
        var courseId = $("#courseId").val();
        var shareKey = getParameter("shareKey");
        if(shareKey!=null && $.trim(shareKey) != ''){
            window.location.href=baseloaction + "/mobile/uc/order/initPayOrder?orderType=COMMON&shopData="+courseId+"-COURSE-1-"+shareKey;
        }else{
            window.location.href=baseloaction + "/mobile/uc/order/initPayOrder?orderType=COMMON&shopData="+courseId+"-COURSE-1";
        }
    }).on('click',"em.icon-hudongpiaoicon05",function () {
        var catalogid= $(this).data('catalogid');
        var courseId = $("#courseId").val();
        var that=$(this);
        downloadDatum(courseId,catalogid,that);
    }).on('click','#free-order',function () {//免费报名
        var _this = $(this);
        var courseId = $("#courseId").val();
        var payType = _this.data('paytype');
        isLogin(function () {
            genFreeOrder(payType,courseId + '-COURSE-1',function () {
                $.toast('免费报名成功');
                checkBuy();
            });
        });
    }).on('click','#c-comment-btn',function () {//显示反馈评分
        isLogin(function () {
            var catalogId = $("#playId").val();
            //评价前做验证
            checkComment(courseId,catalogId,courseFeedback);
        })
    }).on('click','#course-submit-feedback',function () {//提交评论
        var quality = Zepto('#quality').val();
        var teach = Zepto('#teach').val();
        var feel = Zepto('#feel').val();
        var comment = Zepto('#comment').val();
        var courseId = Zepto('#courseId').val();
        var catalogId = Zepto('#playId').val();
        saveComment(quality,teach,feel,comment,courseId,catalogId,function () {
            Zepto('#course-comment-close').trigger('click');
            Zepto('#c-comment-btn').data("eval","已经评论过了")
        });
    }).on('click','.live-play,.chapter-content,.live-tree-trunk,.recent-live-btn',function (e) {//目录点击播放、最近直播播放
        if(status!=1){
            return;
        }
        var _this = $(this);
        if(!$(e).hasClass('now-live-box')){
            _this  = _this.parent('a');
        }

        if(_this.data('id')==null||_this.data('id')==undefined||_this.data('id')<=0){
            return false;
        }
        isLogin(function () {
            var _courseId = _this.data('course');
            var _catalogId = _this.data('id');
            goPlay(_courseId,_courseId,_catalogId,playCallback);
        })
    }).on('click','.download_datum',function(){
        var that= $(this);
        downloadDatum(courseId,$(this).data('catalogid'),that);
    }).on('click',".online-consultation",function(){
        window.open($(this).data("course"),'newwindow', 'toolbar=no,scrollbars=yes,location=no,resizable=no,top=200,left=300,width=800,height=600');
    }).on('click','.now-live-box',function () {
        if(status!=1){
            return;
        }
        var _this = $(this);
        if(_this.data('id')==null||_this.data('id')==undefined||_this.data('id')<=0){
            return false;
        }
        isLogin(function () {
            var _courseId = _this.data('course');
            var _catalogId = _this.data('id');
            goPlay(_courseId,_courseId,_catalogId,playCallback);
        })
    }).on("click","#interact",function(){
        getClass();
    }).on("click","#qa-teacher-btn2",function(){
        if($(this).data("type") == 0){
            $.toast('只能向正在播放的章节问答专家提问');
            return;
        }
        if($(this).data("type") == 2){
            $.toast('当前学习的章节，讲师不是问答专家无法进行提问');
            return;
        }
        window.location.href=baseloaction +'/mobile/teacher/teacherInfo?isCourse=true&teacherId='+$(this).data("id")+"&catalogId="+$("#playId").val()+"&courseId="+courseId;
    }).on("click",".course-class-item",function(){
        window.location.href=baseloaction+"/mobile/class/info?classId="+$(this).data("id");
    }).on("click",".cInfoShare-btn",function(){
        posters( Zepto('#courseName').text(),window.location.href,Zepto('#lookNum').val())
    }).on("click","#playAudition",function(){

      var code =  $(this).data("value");
      if(code==null|| code==undefined|| code==''){
          $.toast('抱歉没有可试听的视频');
          return
      }
        $('.content').scrollTop(0)
        get96krVideoUrlFn({videoIdCode:code});
    }).on("click","#more-liveCatalog-btn",function () {
        var liveCatalog = $('.liveCatalog-List-bx'),
            flag = $(this).data("status")==2?true:false;
        if(flag) {
            liveCatalog.css("height", "auto")
            $(this).text('收起')
            $(this).data("status",1)
        } else {
            liveCatalog.css("height", "5rem")
            $(this).text('展开更多')
            $(this).data("status",2)

        }
    }).on("click","#course-small-comment",function(){
        var params = {
            'courseId':courseId
        };
        params = JSON.stringify(params);
        loadMobilePathData({
            url: baseloaction + '/mobile/course/common/ajaxCourseCommentList',
            contextId: 'course-small-comment-list',
            pageNo: 1,
            pageSize:10,
            pageCall: ajaxCommentList,
            params: params,
            callback: function (pageNo) {
                if(count == null || count == 'undefined' || count == ''){
                    count = 0;
                }
                $("#course-comment-count").text('全部评价('+count+')');
            }
        });
        Zepto.popup('.course-small-read-popup');

    });

    //领取优惠券操作表
    $(document).on('click', '.selectOpcardBtn', function () {
        loadCourseCode(courseId);
    });


    checkBuy();
    var buy = false;
    // 检查课程购买
    function checkBuy() {
        Zepto.ajax({
            url: baseloaction + '/mobile/course/ajax/check/buy',
            data: {'courseId': courseId},
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    buy = true;
                    Zepto('nav.course-info-bar-tab').addClass('mfHide');
                    Zepto(".member-box").css('display','none');
                }else{
                    Zepto('nav.course-info-bar-tab').removeClass('mfHide');
                    Zepto(".member-box").css('display','block');
                }
            },
            error: function () {
                console.log('error');
            }
        });
    }

    /**
     * 播放回调
     * @param material 素材对象
     */
    function playCallback(material){

    }
    var desc =Zepto("#course-summary").val();
    //直播分享
    wShareFn.Focus.init({
        ele: '#c-share-btn',
        opt: checkBaseShare(shareChannel),
        title : Zepto('.ellipsis').text(),
        lookNum : Zepto('#lookNum').val(),
        url :   window.location.href,
        desc : desc,
        reset:true,
        img:Zepto("#courseImg").val()
    });

    /**
     * 加载课程的活动
     */
    setTimeout(function () {
        var price = $("#price").val();
        courseInfoActivity(price);
    },300);

    function  getClass(){

        $.ajax({
            url:baseloaction +'/mobile/class/getCourseRelevanceClasses',
            type:'post',
            dataType:'json',
            data:{
                'courseId':courseId
            },
            success:function (result) {
                if(result.success==true){
                    var entity = result.entity;

                    if(entity.length>0){

                        var html='';
                        entity.forEach(function (item, index) {
                            html+=  '<li data-id='+item.id+' class="wm-whiteBox course-class-item">\n' +
                                '                                            <a  class="text-center">\n' +
                                '                                                <section class="course-class-pic-bx">\n' +
                                '                                                    <img class="wm-img" width="80" height="80"  src="'+item.imageMap.mobileUrlMap.small+'">\n' +
                                '                                                </section>\n' +
                                '                                                <section class="ellipsis-rows">\n' +
                                '                                                    <span class="fs7 c-333">'+item.name+'</span>\n' +
                                '                                                </section>\n' +
                                '                                                <section class="mt5">\n' +
                                '                                                    <span class="fs4 c-888">'+item.topicCount+'个话题</span>\n' +
                                '                                                </section>\n' +
                                '                                            </a>\n' +
                                '                                        </li>'
                        });

                        $(".course-class-item-box").html(html);
                        //获取一个控件的宽度
                        setTimeout(function(){

                            $(".re-class").forEach(function (item, index) {
                                $(item).attr("style","display:black")
                            });
                            $(".course-class-item-box").width( ($('.course-class-item').length+1) *  $('.course-class-item').eq(0).width())
                        },100);

                    };

                }
            }
        });
    }

    setTimeout(function () {
        getNewCatalog(courseId)
    },300)
    /**
     * 获取最新的目录
     * @param courseIds 课程ID串
     * @param courseType 课程类型
     */
    function getNewCatalog(courseIds) {
        $.ajax({
            url: baseloaction +'/mobile/course/getNewCatalog',
            type:'post',
            dataType:'json',
            data:{
                'courseIds':courseIds
            },
            success:function (result) {
                if(result.success==true){
                    var obj = result.entity;
                    if(obj !=null){
                        var context = '';
                        var parentCatalog = obj.parentCatalog;
                        if(parentCatalog != null){
                            context+= parentCatalog.catalogName + "-";
                        }
                        context+= obj.catalogName;
                        $("#last-update").text(context);
                        if(obj.material!=null){
                          var  material =   obj.material;
                          var teacher =     material.teacher;
                          if(teacher!=null){
                            $("#newTeacherName").text("最近授课："+teacher.teacherName);
                          }
                            var assistant =     material.assistant;

                            if(assistant!=null&&assistant.length>0){
                                $("#newAssistantName").text("最近助教："+assistant[0].teacherName);
                                $("#assistant").removeClass("hide");
                            }

                        }

                    }
                }
            }
        });
    }
    isBuy =buy;
});
var isBuy;